﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxCallback;
using System.Configuration;
using System.Web.Security;

namespace TireService.Web.View.AdminView
{
    public partial class ManageBookingLinkNotification : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            if (Page.IsPostBack != true)
            {
                // Bind method dropdown list
                BindMethodDropdownList(db);

                // Show default start and end of present month
                txtStartdate.Value = "01-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString();
                txtEnddate.Value = Convert.ToDateTime("01-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString()).AddMonths(1).AddDays(-1).Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString();
            }

            BindCustomerList(db, Convert.ToDateTime(txtStartdate.Value), Convert.ToDateTime(txtEnddate.Value), Convert.ToInt32(ddlMethod.SelectedItem.Value));
        }

        private void BindMethodDropdownList(TireServiceDB db)
        {
            // Clear method dropdown list
            ddlMethod.Items.Clear();

            // Add default value
            ddlMethod.Items.Add("Alle kunder", -1);

            List<GroupServiceCarSchedule> groupschedules = db.GetGroupServiceCarSchedules(false);

            foreach (GroupServiceCarSchedule groupschedule in groupschedules)
            {
                // Add groupschedule
                ddlMethod.Items.Add(groupschedule.Description, groupschedule.GroupServiceCarScheduleId);
            }
        }

        private List<Customer> FilterCustomers(TireServiceDB db, DateTime StartPeriod, DateTime EndPeriod, int FilterMethod) 
        {
            List<Customer> customers = new List<Customer>();

            // Check method
            if (FilterMethod == -1)
            {
                // Get all active customer subscriptions
                List<CustomerSubscription> customersubscriptions = db.GetCustomerSubscriptionsActive();

                foreach (CustomerSubscription customersubscription in customersubscriptions)
                {
                    // Check if booking link has been send
                    // HACK: Der søges i mail log på subject: "Booking link til mobilhjulskift.dk"
                    List<CustomerMailLog> customermails = db.CustomerMailLogs.Where(p => p.CustomerId == customersubscription.CustomerId & p.SendDate > StartPeriod & p.SendDate < EndPeriod & p.Subject.Contains("Booking link til mobilhjulskift.dk")).ToList();

                    if (customermails.Count > 0)
                    {
                        // Do not show customer - link has been send
                    }
                    else
                    {
                        // Show all customers

                        // Check if customer already added (if customer has ex. 2 cars and subscriptions)
                        if (customers.Any(p => p.CustomerId == customersubscription.CustomerId))
                        {
                            // Already exist in list
                        }
                        else
                        {
                            // Get Customer
                            Customer customer = db.GetCustomer(customersubscription.CustomerId);

                            // Add customer to list
                            customers.Add(customer);
                        }
                    }
                }
            }
            else
            {
                // Use groupservice bookings
                int GroupServiceCarScheduleId = Convert.ToInt32(ddlMethod.SelectedItem.Value);

                GroupServiceCarSchedule groupschedule = db.GetGroupServiceCarSchedule(GroupServiceCarScheduleId);

                if (groupschedule == null | groupschedule.InActive)
                {
                    // Error
                }
                else
                {
                    Customer parentcustomer = db.GetCustomer(groupschedule.CustomerId);

                    List<Customer> companyCustomers = db.GetCustomersForParentCustomer(groupschedule.CustomerId);

                    companyCustomers.Add(parentcustomer);

                    foreach (Customer companyCustomer in companyCustomers)
                    {
                        // Check if booking link has been send
                        // HACK: Der søges i mail log på subject: "Booking link til mobilhjulskift.dk"
                        List<CustomerMailLog> customermails = db.CustomerMailLogs.Where(p => p.CustomerId == companyCustomer.CustomerId & p.SendDate > StartPeriod & p.SendDate < EndPeriod & p.Subject.Contains("Booking link til mobilhjulskift.dk")).ToList();

                        if (customermails.Count > 0)
                        {
                            // Do not show customer - link has been send
                        }
                        else
                        {
                            // Check if any active subscriptions exists for customer
                            List<CustomerSubscription> customersubscriptions = db.GetCustomerSubscriptionsActive(companyCustomer.CustomerId);

                            if (customersubscriptions.Count > 0)
                            {
                                foreach (CustomerSubscription customersubscription in customersubscriptions)
                                {
                                    if (!customersubscription.InActive)
                                    {
                                        // Check if car / tiresets are related to container / warehouse
                                        List<TireSet> tiresets = db.GetTireSetsForCustomer(customersubscription.CustomerId).Where(p => p.ContainerCargoRoomId != null).ToList();

                                        foreach (TireSet tireset in tiresets)
                                        {
                                            ContainerCargoRoom cargoroom = db.GetContainerCargoRoom(Convert.ToInt32(tireset.ContainerCargoRoomId));

                                            if (cargoroom.ContainerId == groupschedule.ContainerId)
                                            {
                                                // Check if customer already added (if customer has ex. 2 cars and subscriptions)
                                                if (customers.Any(p => p.CustomerId == companyCustomer.CustomerId))
                                                {
                                                    // Already exist in list
                                                }
                                                else
                                                {
                                                    // Add customer to list
                                                    customers.Add(companyCustomer);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return customers;
        }

        private void BindCustomerList(TireServiceDB db, DateTime StartPeriod, DateTime EndPeriod, int FilterMethod) 
        {
            gvCustomer.DataSource = FilterCustomers(db, StartPeriod, EndPeriod, FilterMethod).ToList();
            gvCustomer.DataBind(); 
        }


        /// <summary>
        /// Postback function that updates gridview with services
        /// </summary>
        protected void gvCustomer_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            // 0: Startdate, 1: Enddate, 2: FilterMethod
            string[] param = e.Parameters.Split('|');

            BindCustomerList(db, Convert.ToDateTime(param[0]), Convert.ToDateTime(param[1]), Convert.ToInt32(param[2]));
        }

        protected void callSendBookingLinkEmail_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                // Array for servicetask log (1: CustomerId, 2: Action and description (Ok, Failed))
                Dictionary<int, string> bookingemail_log = new Dictionary<int, string>();

                // Instantiate email service
                EmailNotificationServices emailService = new EmailNotificationServices();

                // 0: Startdate, 1: Enddate, 2: FilterMethod
                string[] param = e.Parameter.Split('|');

                TireServiceDB db = new TireServiceDB();

                DateTime StartPeriod = Convert.ToDateTime(param[0]);
                DateTime EndPeriod = Convert.ToDateTime(param[1]);
                int FilterMethod = Convert.ToInt32(param[2]);

                List<Customer> customers = FilterCustomers(db, StartPeriod, EndPeriod, FilterMethod);

                if (FilterMethod == -1)
                {
                    // Send to individual customer

                    foreach (Customer customer in customers.Take(Convert.ToInt32(ddlEmailCount.SelectedItem.Value)))
                    {
                        // Send email to customer with booking link
                        if (customer.UserId != null)
                        {
                            try
                            {
                                string BookingLink = string.Format(ConfigurationManager.AppSettings["Website"] + "Booking/Booking.aspx?uid={0}", customer.UserId.ToString());

                                emailService.CustomerBookingLink_SendCustomerEmail(customer.Email, customer.Name, customer.CustomerId, Membership.GetUser(), BookingLink);

                                // OK
                                bookingemail_log.Add(customer.CustomerId, "OK - Booking link blev afsendt");
                            }
                            catch (Exception)
                            {
                                // Error
                                bookingemail_log.Add(customer.CustomerId, "FEJL - Booking link blev IKKE afsendt");
                            }
                        }
                        else
                        {
                            // Error
                            bookingemail_log.Add(customer.CustomerId, "FEJL - Booking link blev IKKE afsendt, UserId er tom");
                        }
                    }
                }
                else
                {
                    // Send to groupschedule customers

                    // Get GroupSchedule
                    GroupServiceCarSchedule groupschedule = db.GetGroupServiceCarSchedule(FilterMethod);

                    if (groupschedule.InActive | groupschedule == null)
                    {

                    }
                    else
                    {
                        foreach (Customer customer in customers)
                        {
                            try
                            {
                                string BookingLink = string.Format(ConfigurationManager.AppSettings["Website"] + "Booking/GruppeBooking.aspx?id={0}", groupschedule.GroupGuid.ToString());

                                emailService.CustomerBookingLink_SendCustomerEmail(customer.Email, customer.Name, customer.CustomerId, Membership.GetUser(), BookingLink);

                                // OK
                                bookingemail_log.Add(customer.CustomerId, "OK - Gruppe booking link blev afsendt");
                            }
                            catch (Exception)
                            {
                                // Error
                                bookingemail_log.Add(customer.CustomerId, "FEJL - Gruppe booking link blev IKKE afsendt");
                            }
                        }
                    }   
                }

                // Return log on email sendings to finance email
                string logHTML = "<b>Afsendelse af booking links</b><br><table><tr><td>Kundenr</td><td>Status og handling</td></tr>";
                foreach (KeyValuePair<int, string> log in bookingemail_log)
                {
                    logHTML += "<tr><td>" + log.Key.ToString() + "</td><td>" + log.Value + "</td></tr>";
                }
                logHTML += "</table>";

                string Subject = "Afsendelse af booking links";
                emailService.SendFinanceInternalEmailNotification(Subject, logHTML);
            }
            catch (Exception ex)
            {
                
            }
        }
    }
}